from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api.labs.taskqueue import TransientError

from marketdata.models import MarketStatsMail,MarketStatsAttach
from marketdata.statistic import MaxSymbolsInAttach
from mail.reader import MailMarketStatReader
from datetime import  datetime

import logging



class MailHandler(InboundMailHandler):
    def receive(self, message):
        _bodies = ""
        for body in message.bodies(content_type='text/plain'):
            _body=body[1].decode()
            if isinstance(_body, unicode):
                _body = _body.encode('utf-8')   
            _bodies += "\n" + _body
            db.run_in_transaction(self.store_result,message.sender,message.subject,message.date,_bodies)
        pass

    def store_result(self, _sender, _subject, _date, _body):
        _len = len(_body)
        if _len > 126:
            _today = datetime.today()
            _key = "%s%9d" % (str(_today), _len)
            inboundmail = MarketStatsMail(sender = _sender, subject = _subject, date = _date, datasize = _len, key_name = _key)
            inboundmail.statsdata = []
#            inboundmail.put()
            logging.info("Total len = %d." % (_len))
            _current = 127
            while _current < _len:
                if (_len - _current) < MaxSymbolsInAttach :
                    _next = _len
                else:
                    _next = _body.rfind("\n",_current,_current + MaxSymbolsInAttach)+1
                logging.info("current pos = %d, next pos = %d" % (_current,_next))
                inboundattach = MarketStatsAttach(parent = inboundmail)
                inboundattach.statsdata = db.Text( _body[_current:_next])
                inboundattach.put()
                inboundmail.statsdata.append(inboundattach.key().id())
                logging.info("attach id = %d." % (inboundattach.key().id()))
                _current = _next
            inboundmail.put()
            _reader = MailMarketStatReader()
            logging.info("Try to continue via deferrer wit ID = %s." % (_key))
            try:
                _reader.run(_key)
            except TransientError:
                logging.info("TransientError!. Retry to continue via deferrer wit ID = %s." % (_key))
                _reader.run(_key)
        pass

application = webapp.WSGIApplication([MailHandler.mapping()], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

